/*
 *  file-name: wshm.c
 *  
 *  date: 2019-4-5
 *
 *  desc: IPC shared memory
 *
 */


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main()
{
  //create IPC key
  key_t key = ftok("./", 66);
  int* pp = NULL;
  void* addr = NULL;

  //create shared memory, return an ID
  int shmid = shmget(key, 100, IPC_CREAT|IPC_EXCL|0666);
  if(shmid == -1)
  {
    perror("shmget");
    return 1;
  }

  //detach the shared memory
  addr = shmat(shmid, 0, 0);
  if((void *)-1 == addr)
  {
    perror("shmat");
    return 1;
  }

  //write to shared memory
  pp = (int*)addr;
  *pp = 0x12312312;
  *(pp + 1) = 0x6fffffff;

  //destory detach
  if(-1 == shmdt(addr))
  {
    perror("shmdt");
    return 1;
  }
  printf("shmdt is successful\n");
  getchar();

  //delete shared memory
  if(-1 == shmctl(shmid, IPC_RMID, NULL))
  {
    perror("shmctl");
    return 1;
  }

  return 0;
}
